<script>
  import L from 'leaflet';
  // import { WGS84ToGCJ02 } from 'istrong-map-coordinate-transformation';
  import { isEmpty, cloneDeep, orderBy } from 'lodash';
  import vgMap from '../../components/Map.vue';
  import Position from '../../libs/leaflet-positionmarker';

  let sortByField = (data) => {
    let ls = orderBy(data, [function (o, a) {
      return o.options.feature.is_over;
    }, function (o, a) {
      return o.options.feature.fVal;
    }], ['desc', 'desc']);
    return ls;
  }
  let waterLegends = {
    "warn": require('../../assets/water/water-warn.png'),
    "up": require('../../assets/water/water-up.png'),
    "down": require('../../assets/water/water-down.png'),
    "normal": require('../../assets/water/water-normal.png')
  }
  export default {
    name: 'waterMap',
    components: {
      'vg-map': vgMap
    },
    props: {
      beginTime: {
        type: String,
        required: true
      },
      endTime: {
        type: String,
        required: true
      },
      data: {
        type: Array,
        default: []
      },
      positionMarker: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        crs: 'EPSG3857',
        zoom: 8,
        center: [26, 119],
        baseLayers: [],
        thematicLayers: [],
        zoomControl: {},
        layersControl: {},
        vStationLayerName: 'vWaterStation',//矢量站点名称
        vStationMarkers: {}
      }
    },
    watch: {
      data: function (val) {
        this._loadVStationsToMap();
      },
      positionMarker: function (val) {
        this._startPosition();
      }
    },
    mounted() {
      this._loadVStationsToMap();
      this._startPosition();
    },
    methods: {
      _loadVStationsToMap() {
        let vMap = this.$refs.map;
        vMap.clearLayer(this.vStationLayerName);
        if (!this.data || this.data.length === 0) {
          return;
        }
        let layerOpts = {
          latlngBounds: L.latLngBounds([-20, 60], [60, 200]),
          onlyCollisionTooltip: true,
          markerOffset: [1, 1],
          tooltipOffset: [0, 0],
          map: vMap.Map,
          sortByField: sortByField
        };
        this.vStationMarkers = {};
        vMap.addCollisionLayer(this.vStationLayerName, layerOpts, this.data, this._vStationsMarkerInit)
      },
      _vStationsMarkerInit(stationInfo, layer) {
        stationInfo.lat = stationInfo.lat || stationInfo.latitude;
        stationInfo.lng = stationInfo.lng || stationInfo.longitude;
        if (!stationInfo.lat || !stationInfo.lng) {
          return;
        }
        stationInfo.id = stationInfo.id || stationInfo._id;
        let vector = this.vStationMarkers;
        // let gcj02 = WGS84ToGCJ02({ lng: stationInfo.lng, lat: stationInfo.lat });
        let latlng = L.latLng(stationInfo.lat, stationInfo.lng);
        if (vector[stationInfo.id]) {
          layer.removeLayer(vector[stationInfo.id]);
        }

        let wptn = Math.floor(stationInfo.water_potential || stationInfo.wptn);
        let iconIndex = stationInfo.is_over ? 'warn' : (
          wptn === 4 ? 'down' : wptn === 5 ? 'up' : 'normal');

        let marker = new L.Marker(latlng,
          {
            icon: L.icon({
              iconUrl: waterLegends[iconIndex],
              iconSize: [14, 14],
              iconAnchor: [7, 7]
            }),
            minZoom: 4,
            feature: stationInfo
          });
        marker.on('click', this._showChartInfo, this);

        let toolTip = (new L.Tooltip({
          permanent: false,
          interactive: true,
          direction: 'right',
          offset: [6, 0],
          mapPreclickToClose: false,
          className: 'commonTooltip',
          feature: stationInfo
        }, marker)).setContent(stationInfo.name + (stationInfo.val !== undefined ? '<br/>' + stationInfo.val : ''));
        toolTip.on('click', this._showChartInfo, this);
        marker.bindTooltip(toolTip);

        vector[stationInfo.id] = marker;
        return marker;
      },
      _showChartInfo(e) {
        let feature = e.target.options.feature;
        this.$emit('showChartInfo', feature);
      },
      onChangeShowType() {
        this.$emit('changeShowType', 'list');
      },
      onOpenFilterPanel() {
        this.$emit('setFilterConditions', true);
      },
      _startPosition() {
        if (this.positionMarker === '') {
          return;
        }
        Position.startPosition(this, this.$refs.map.Map, this.positionMarker, this.vStationMarkers);
        this.$emit('positionEnd');
      }
    },
    created() {
      let mapConfig = this.$AppConfig.map;
      this.crs = mapConfig.crs;
      this.zoom = mapConfig.zoom;
      this.center = mapConfig.center;
      this.baseLayers = cloneDeep(mapConfig.baseLayers);
      this.thematicLayers = cloneDeep(mapConfig.thematicLayers);
      this.zoomControl = mapConfig.zoomControl;
      this.layersControl = mapConfig.layersControl;

      let moduleConfig = mapConfig.module ? mapConfig.module.water : null;
      if (moduleConfig) {
        let baseLayer = moduleConfig.baseLayer;
        if (baseLayer) {
          this.baseLayers.forEach(item => {
            item.checked = (item.id === baseLayer ||
              item.name === baseLayer);
          });
        }
        this.zoom = moduleConfig.zoom || this.zoom;
        this.center = moduleConfig.center || this.center;
        if (!isEmpty(moduleConfig.thematicLayers)) {
          let thematicLayers = [];
          this.thematicLayers.forEach(item => {
            if (moduleConfig.thematicLayers[item.id + '']) {
              thematicLayers.push(assign(item, moduleConfig.thematicLayers[item.id + '']));
            }
          });
          this.thematicLayers = thematicLayers;
        }
      }
    },
    beforeDestroy() {
    }
  }
</script>
<template>
  <div id="mapViewer">
    <vg-map :crs="crs" :baseLayers="baseLayers" :thematicLayers="thematicLayers" :zoom="zoom" :center="center" :zoomControl="zoomControl"
      :layersControl="layersControl" ref="map"></vg-map>
    <div class="mapViewer-TopRight-Controls">
      <div class="btChangeRouterList" @click="onChangeShowType">
        <span class="ion-ios-list"></span>
      </div>
      <div class="mapViewer-ButtonFilter" @click="onOpenFilterPanel">
        <img src="../../assets/filter.png" />
      </div>
    </div>
  </div>
</template>
<style>
</style>